﻿#region header

//  ***************************************************************************
// *                                LICENSE
//  ***************************************************************************
//  * "Haplous" .NET Simple 2D Game Framework
//  * 
//  * Copyright © Jonathan Evans 2014-2014
//  * 
//  * This program is free software; you can redistribute it and/or
//  * modify it under the terms of the GNU General Public License
//  * as published by the Free Software Foundation; either version 2
//  * of the License, or (at your option) any later version.
//  * 
//  * This program is distributed in the hope that it will be useful,
//  * but WITHOUT ANY WARRANTY; without even the implied warranty of
//  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  * GNU General Public License for more details.
//  * 
//  * You should have received a copy of the GNU General Public License
//  * along with this program; if not, write to the Free Software
//  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//  * 
//  ***************************************************************************
//  * 
//  * Contact: opencollar@googlemail.com
//  * 
//  * Website: http://haplous.codeplex.com/
//  *
//  * NuGet:   http://www.nuget.org/packages/haplous/
//  *
//  * File:    Haplous/Haplous/WallHuggingDirector.cs
//  *
//  ***************************************************************************

#endregion

using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

using Haplous.Properties;

using JetBrains.Annotations;

namespace Haplous
{
    /// <summary>
    ///     A controller that attempts to keep the ghost hugging a wall to its left or right.
    /// </summary>
    [SuppressMessage("Microsoft.Maintainability", "CA1501:AvoidExcessiveInheritance")]
    [DebuggerDisplay("WallHuggingDirector: Name={Name}")]
    public abstract class WallHuggingDirector : SynchronizedDirector
    {
        /// <summary>
        ///     The direction, relative to the direction of travel, to which we should always keep a wall.  Must be either
        ///     <see cref="DirectionKind.Left" /> or <see cref="DirectionKind.Right" />.
        /// </summary>
        private readonly DirectionKind _huggingWall;

        /// <summary>
        ///     The offset used when looking ahead for a wall
        /// </summary>
        [NotNull]
        private readonly PositionInt32 _offsetAhead = new PositionInt32(0, 0);

        /// <summary>
        ///     The offset used when looking aside for a wall.
        /// </summary>
        [NotNull]
        private readonly PositionInt32 _offsetAside = new PositionInt32(0, 0);

        /// <summary>
        ///     The maximum size of any step.
        /// </summary>
        private readonly int _step;

        /// <summary>
        ///     Initializes a new instance of the <see cref="ElementBase" /> class.
        /// </summary>
        /// <param name="game">
        ///     The game to which the class belongs.  The <paramref name="game" /> must not be
        ///     <see langword="null" />.
        /// </param>
        /// <param name="name">
        ///     The unique name that can be used to identify this object.  The <paramref name="name" /> must not be
        ///     <see langword="null" />, empty or all whitespace.
        /// </param>
        /// <param name="actor">The Actor to control.  Must not be <see langword="null" />.</param>
        /// <param name="cue">The Cue that will be used to trigger movements.</param>
        /// <param name="initialDirection">The initial direction in which to move.</param>
        /// <param name="huggingWall">
        ///     The direction, relative to the direction of travel, to which we should always keep a wall.
        ///     Must be either <see cref="DirectionKind.Left" /> or <see cref="DirectionKind.Right" />.
        /// </param>
        /// <param name="stepSize">The size of each movement (in game pixels). Must be greater than zero.</param>
        /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="stepSize" /> must be greater than zero. </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        ///     Only <see cref="DirectionKind.Left" /> and
        ///     <see cref="DirectionKind.Right" /> are valid values of the <paramref name="huggingWall" /> argument.
        /// </exception>
        protected WallHuggingDirector([NotNull] Game game, [NotNull] string name, [NotNull] Actor actor, [NotNull] Cue cue, DirectionKind initialDirection, DirectionKind huggingWall, int stepSize)
            : base(game, name, actor, cue)
        {
            switch(huggingWall)
            {
                case DirectionKind.Left:
                    break;
                case DirectionKind.Right:
                    break;
                default:
                    throw new ArgumentOutOfRangeException("huggingWall", huggingWall, Resources.Error_HuggingWallArgumentInvalid);
            }

            if(stepSize <= 0)
                throw new ArgumentOutOfRangeException("stepSize", stepSize, Resources.Error_StepSizeArgumentInvalid);
            _step = stepSize;
            _offsetAhead.Y = _step;
            _huggingWall = huggingWall;
            CurrentDirection.Value = initialDirection;
        }

        /// <summary>
        ///     Called when an update is required.
        /// </summary>
        protected override void OnTick()
        {
            TryMove(0);
        }

        /// <summary>
        ///     Try to move.
        /// </summary>
        /// <param name="attempt">The number of attempts previously tried.</param>
        private void TryMove(int attempt)
        {
            if(attempt >= 3)
                return; // There is nowhere we can go.

            // Is there a wall to our side to hug?
            _offsetAside.Y = Actor.Size.Width + (_step / 2);
            var potentialWalls = CurrentDirection.HitTest(Game, Actor.Position, _offsetAside, _huggingWall, Actor.Size).ToArray();
            var walls = potentialWalls.Where(IsWall).ToArray();
            if(walls.Length <= 0)
            {
                // There is no wall - we must turn
                CurrentDirection.Rotate(_huggingWall);
            }

            if(CurrentDirection.Value != DirectionKind.None)
            {
                var relativePosition = CurrentDirection.Translate(_offsetAhead);

                ConfineToGameArea(relativePosition);
                Move(relativePosition);
            }
        }

        /// <summary>
        ///     Determines whether the specified candidate is a wall.
        /// </summary>
        /// <param name="candidate">The candidate to test.</param>
        /// <returns><see langword="true" /> if the specified candidate is wall; otherwise, <see langword="false" />.</returns>
        protected abstract bool IsWall([NotNull] SolidGraphicBlock candidate);
    }
}